import { AbstractButton, Icon, Layout, UserSubPageBase } from "@/components";
import { colors } from "@/data/shared/colors";
import { TITLES_SELECT } from "@/data/user/userData";
import {
  useUserInfo,
  addUserAddress,
  removeUserAddress,
} from "@/store/userDataContext";
import {
  Input,
  Label,
  Picker,
  Radio,
  RadioGroup,
  View,
} from "@tarojs/components";
import { useEffect, useState } from "react";
import style from "./index.module.scss";
import { useAuth } from "@/store/authContext";

export default function AddressDetailsEdit() {
  const { dispatchAuthAction } = useAuth();
  const { addressEditData } = useUserInfo().userInfoState;
  const { userInfoState, dispatchUserDataAction, requestWechatAddress } =
    useUserInfo();
  const { userData } = userInfoState;
  const [name, setName] = useState(addressEditData?.name ?? null);
  const [phone, setPhone] = useState(addressEditData?.phone ?? null);
  const [region, setRegion] = useState(addressEditData?.residenceArea ?? null);
  const [address, setAddress] = useState(addressEditData?.address ?? null);
  const [isPrimary, setIsPrimary] = useState(
    addressEditData?.isPrimary ?? true
  );

  const addAddress = () => {
    const query: any = {
      address: region,
      detail: address,
      realName: name,
      phone: phone,
      isDefault: isPrimary,
    };
    if (addressEditData?.id) {
      query.id = addressEditData?.id;
    }
    addUserAddress(dispatchUserDataAction, userData!, {
      query: query,
      authDispatch: dispatchAuthAction,
    });
  };

  const deleteAddress = () => {
    if (addressEditData?.id) {
      removeUserAddress(dispatchUserDataAction, {
        query: { id: addressEditData.id },
        authDispatch: dispatchAuthAction,
      });
    }
  };

  // Null [new entry] -> Coerce to boolean false, else simply get field (double cooersion)
  const canDelete = !!addressEditData?.canBeDeleted;

  return (
    <Layout>
      <UserSubPageBase title="请输入收件人联系方式及地址">
        <View className={style.form}>
          <View className={style["input-section"]}>
            <Label>姓名</Label>
            <Input
              className={style.input}
              type="text"
              onInput={(e) => {
                setName(e.detail.value);
              }}
              value={name ?? undefined}
              placeholder={"请填写姓名"}
              placeholderStyle={`color: ${colors.colorDark}`}
            />
          </View>
          {/* Phone */}
          <View className={style["input-section"]}>
            <Label>电话</Label>
            <Input
              className={style.input}
              type="number"
              onInput={(e) => {
                setPhone(e.detail.value);
              }}
              value={phone ?? undefined}
              placeholder={"请填写收货人手机号"}
              placeholderStyle={`color: ${colors.colorDark}`}
            />
          </View>
          {/* Region */}
          <View className={style["input-section"]}>
            <Label>省-市-区</Label>
            <Picker
              className={style.input}
              mode="region"
              onChange={(e) => {
                setRegion(e.detail.value);
              }}
              value={region ? region : []}
            >
              <View className={style.flex}>
                <View>{region ? region.join("-") : "请选择"}</View>
                <Icon className={style.down} type="DownChevron" />
              </View>
            </Picker>
          </View>
          {/* Address */}
          <View className={style["input-section"]}>
            <Label>详细地址</Label>
            <Input
              className={style.input}
              type="text"
              onInput={(e) => {
                setAddress(e.detail.value);
              }}
              value={address ?? undefined}
              placeholder={"请填写详细地址"}
              placeholderStyle={`color: ${colors.colorDark}`}
            />
          </View>
          {/* Is Primary */}
          <View
            className={`${style["input-section"]} ${style["input-section-horizontal"]}`}
          >
            <Label className={style["is-primary-label"]}>
              是否设为首选地址？
            </Label>

            <RadioGroup
              className={style["radio-group"]}
              onChange={(e) => {
                setIsPrimary(!!e.detail.value);
              }}
            >
              {[
                // Starting point -> assuming edited address should be set to primary
                // to be set as default for Cart-shipping
                { value: "true", checked: true, text: "是" },
                { value: "false", checked: false, text: "否" },
              ].map((item, i) => {
                return (
                  <Label key={i}>
                    <Radio
                      value={item.value}
                      checked={item.checked}
                      color={colors.colorGrey}
                    >
                      <View className={style["label"]}>{item.text}</View>
                    </Radio>
                  </Label>
                );
              })}
            </RadioGroup>
          </View>
        </View>
        {/* Submit button */}
        <View className={style["submit-button"]}>
          {canDelete && (
            <AbstractButton
              color="transparent"
              onClick={() => {
                deleteAddress();
              }}
            >
              删去
            </AbstractButton>
          )}
          <AbstractButton
            color="dark"
            onClick={() => {
              addAddress();
              //Taro.navigateBack();
            }}
          >
            完成
          </AbstractButton>
        </View>
      </UserSubPageBase>
    </Layout>
  );
}
